package indi.caibo.service_mail.controller;

import indi.caibo.commonutils.R;
import indi.caibo.commonutils.RandomUtil;
import indi.caibo.service_mail.service.MailService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

/**
 * @author Bo Cai
 * @version 1.0
 * @date 2021/11/23 15:07
 */
@Api(tags = "邮件模块")
@RestController
@RequestMapping("/mail-service/mail")
public class MailController {
    @Autowired
    private MailService mailService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @GetMapping("send-verification-code/{mailUrl}")
    @ApiOperation(value = "发送验证码邮件")
    private R send(@PathVariable String mailUrl) {
        /*验证码还没过期，就不要再次发送*/
        String verificationCode = redisTemplate.opsForValue().get(mailUrl);
        if (!StringUtils.isEmpty(verificationCode)) return R.ok().message("验证码已经成功发送，五分钟内请不要重复操作！");
        if (!StringUtils.isEmpty(verificationCode)) return R.ok().message("验证码已经成功发送，五分钟内请不要重复操作！");

        verificationCode = RandomUtil.getFourBitRandom();
        if (mailService.sendVerificationCode(mailUrl,  verificationCode)) {
            redisTemplate.opsForValue().set(mailUrl, verificationCode, 5, TimeUnit.MINUTES);
            return R.ok().message("邮件发送成功！");
        } else return R.error().message("邮件发送失败");
    }
}